package org.example.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@Controller
public class LabelController {

    /**
     *
     * @param code 一维码的内容
     * @param mv
     * @return
     */
    @RequestMapping("/genPdf/{code}")
    public String a(@PathVariable("code") String code , ModelAndView mv){
        mv.addObject("barCode" , code);

        return "index";
    }

    /**
     * 生成一维码的图片，
     * @param code 一维码内容
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/bar/{code}.png")
    public void bar(@PathVariable("code") String code ,  HttpServletRequest request , HttpServletResponse response) throws IOException {
        generateCode(code , 500 , 100 , response.getOutputStream());
    }

    /**
     * @param code    一维码存储的数据信息
     * @param width   生成图片的宽度 ， 长宽会决定一维码的大小，和清晰度
     * @param height  生成图片的高度 ， 长宽会决定一维码的大小，和清晰度
     * @return void
     * */
    public static void generateCode(String code, int width, int height , OutputStream out){
        // 定义位图矩阵BitMatrix
        BitMatrix matrix = null;
        try {
            // 使用code_128格式进行编码生成100*25的条形码
            MultiFormatWriter writer = new MultiFormatWriter();

            matrix = writer.encode(code, BarcodeFormat.CODE_128, width, height, null);
        } catch (WriterException e) {
            e.printStackTrace();
        }

        // 将位图矩阵BitMatrix保存为图片
        try {
            BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix);
            ImageIO.write(image, "png", out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
